/* eslint-disable complexity */

/**
 * 提取输入数据的桩号信息
 * @param {string} inputData 输入数据
 * @returns 提取的桩号信息
 */
function extractPiles (inputData) {
  let inputPiles = null
  let pileNoPrefix = null
  let startPile = null
  let startPileNo = null
  let endPile = null
  let endPileNo = null
  let fullPile = null

  if (typeof inputData !== 'string' || !inputData) {
    return {
      inputPiles,
      pileNoPrefix,
      startPile,
      startPileNo,
      endPile,
      endPileNo,
      fullPile
    }
  }

  // 提取输入的完整桩号字符
  const matchArray1 = inputData.match(/[A-Za-z]?K[A-Za-z0-9.+\-~,]*/gi)

  // 拆分开始、结束桩号
  let splitPiles = []
  if (matchArray1 !== null) {
    inputPiles = matchArray1[0]

    const matchArray2 = matchArray1.toString().match(/([A-Za-z]?K([\d+.]*)|([\d+.]*))/gi)

    if (matchArray2 !== null) {
      splitPiles = matchArray2.filter((i) => i)
    }
  }
  startPile = splitPiles[0] || null
  endPile = splitPiles[1] || null

  // 结束桩号修正
  if (startPile && endPile && endPile.match(/K/gi) === null) {
    const prefix = startPile.split('+')[0]
    if (prefix) {
      endPile = `${prefix}+${endPile}`
    }
  }

  // 开始桩号、开始里程格式化
  if (startPile) {
    startPile = startPile.toUpperCase()
    startPileNo = startPile.replace(/[A-Z]|\+/g, '')
    pileNoPrefix = startPile.replace(/\d|\+|\./g, '')
  }

  // 结束桩号、结束里程格式化
  if (endPile) {
    endPile = endPile.toUpperCase()
    endPileNo = endPile.replace(/[A-Z]|\+/g, '')
  }

  // 生成完整桩号
  if (startPile || endPile) {
    fullPile = [startPile, endPile].filter((i) => i).join('~')
  }

  return {
    inputPiles,
    pileNoPrefix,
    startPile,
    startPileNo,
    endPile,
    endPileNo,
    fullPile
  }
}

module.exports = {
  extractPiles
}
